<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\ExamUserAnswer as ExamUserAnswerModel;
use app\admin\model\ExamUserPaper as ExamUserPaperModel;
use app\admin\model\ExamQuestion as ExamQuestionModel;

class ExamReview extends Backend
{
    // 列表：获取所有待批阅的简答题（按答卷分组）
    public function index(): void
    {
        // 返回答卷列表（exam_user_paper） —— 只包含存在未批阅简答题的答卷
        $paperId = $this->request->get('paper_id');
        $userId = $this->request->get('user_id');

        $answerQuery = ExamUserAnswerModel::where('type', 'short')->where('is_reviewed', 0);
        $userPaperIds = $answerQuery->column('user_paper_id');
        $userPaperIds = array_unique($userPaperIds ?: []);
        $list = ExamUserPaperModel::whereIn('id', $userPaperIds);
        if ($paperId) {
            // filter answers by questions that belong to the paper
            $list = $list->whereIn('paper_id', $paperId);
        }
        if ($userId) {
            $list = $list->where('user_id', $userId);
        }

        $list = $list->order('id desc')->select();

        $this->success('', $list);
    }

    // 获取某答卷的简答题详情
    public function detail(): void
    {
        $user_paper_id = $this->request->get('user_paper_id');
        $user_id = $this->request->get('user_id');
        if (!$user_paper_id && !$user_id) $this->error('参数错误');
        if ($user_paper_id) {
            $answers = ExamUserAnswerModel::where(['user_paper_id' => $user_paper_id, 'type' => 'short'])->select();
        } else {
            $answers = ExamUserAnswerModel::where(['user_id' => $user_id, 'type' => 'short'])->select();
        }
        $questions = [];
        foreach ($answers as $a) {
            $q = ExamQuestionModel::find($a->question_id);
            $questions[] = ['answer' => $a, 'question' => $q];
        }
        $this->success('', ['answers' => $questions]);
    }

    // 保存评分
    public function save(): void
    {
        $data = $this->request->post('scores'); // [{answer_id:1, score:5}, ...]
        if (!$data || !is_array($data)) $this->error('参数错误');
        $totalAdd = 0;
        $userPaperId = 0;
        foreach ($data as $item) {
            $ans = ExamUserAnswerModel::find($item['answer_id']);
            if (!$ans) continue;
            $ans->score = (int)$item['score'];
            $ans->is_reviewed = 1;
            $ans->save();
            $totalAdd += (int)$item['score'];
            $userPaperId = $ans->user_paper_id;
        }
        // 更新考生答卷总分
        if ($userPaperId) {
            $paper = ExamUserPaperModel::find($userPaperId);
            if ($paper) {
                $paper->score = $paper->score + $totalAdd;
                $paper->save();
            }
        }
        $this->success('保存成功');
    }
}
